from google.appengine.ext import db
from datetime import datetime, timedelta
import random, string

from _user import _User

def expireTime():
    return datetime.utcnow() + timedelta(days=14)

def randomString(length=16):
    return ''.join((random.choice(string.ascii_letters + string.digits) for _ in range(length)))

class _Session(db.Model):
    '''
     Session Model, Stores session id and other related properties
     use the key_name value as the id of the session
    '''
    
    expireAt = db.DateTimeProperty(required=True)
    user = db.ReferenceProperty(_User, required=False)
    
    def updateExpireTime(self):
        self.expireAt = expireTime()
    
    @property
    def session_id(self):
        return self.key().name()
    
    @classmethod
    def create_session(cls):
        ''' create a new session in a transaction '''
        return db.run_in_transaction(cls._create_session)
    
    @classmethod
    def _create_session(cls):
        ''' create a new session '''
        key = randomString()
        while cls.get_by_session_id(key):
            key = randomString()
        session = _Session(key_name=key, expireAt=expireTime())
        session.put()
        return session
    
    @classmethod
    def get_by_session_id(cls, id):
        ''' get a session for a specified id or None if not found '''
        session = cls.get_by_key_name(key_names=id, parent=None)
        if session:
            session.updateExpireTime()
            session.put()
        return session

    def invalidate(self):
        self.user = None
        self.put()
